package xyz.zhno.project.commons.core.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * JWT 工具类
 * @author zh_o
 * @date 2020-10-31
 */
public class JwtUtils {

    /**
     * JWT 签名密钥
     */
    private static final SecretKey JWT_KEY = Keys.hmacShaKeyFor("eyJhb#*iJ9!yJqdGkiOiJqd$%nN1YiI6IntcImlkXCI6XC%&!^G5hbWU6eGlhb2hvbmcscGFzc3dvcmQ6MTIzfSIsImV4cCI6MTU1Nj".getBytes());

    /**
     * 创建令牌
     * @param payload 有效载荷
     * @return Token
     */
    public static String getToken(Map<String, Object> payload) {
        // 默认过期时间为 15 天
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 15);

        return Jwts.builder().setClaims(payload)
                .setExpiration(calendar.getTime())
                .setClaims(payload)
                .signWith(JWT_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 创建令牌自定义过期时间
     * @param payload 有效载荷
     * @param expireTime 有效时间
     * @return Token
     */
    public static String getToken(Map<String, Object> payload, Date expireTime) {
        return Jwts.builder()
                .setClaims(payload)
                .setExpiration(expireTime)
                .setClaims(payload)
                .signWith(JWT_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * JWT 解析
     * @param token 传入 Token
     * @return 令牌信息
     */
    public static Claims verify(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(JWT_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

}
